Use theJColorChooser
class to provide users with a palette of colors to choose from. A color chooser is a component that you can place anywhere within your program's GUI. TheJColorChooser
API also makes it easy to bring up a dialog (modal or not) that contains a color chooser.Here's a picture of an application that uses a color chooser to set the text color in a banner:
[PENDING: We'll update the snapshot and add call-outs to various parts of the color chooser:
- color chooser (everything inside and including the "Choose Text Color" border)
- preview panel (everything inside and including the "Preview" border)
- chooser panel (everything inside but NOT including the tabbed pane)]
You can run ColorChooserDemo using JavaTM Web Start. The source code for the program is in
ColorChooserDemo.java
.The color chooser consists of everything within the box labeled Choose Text Color. This is what a standard color chooser looks like in the Java Look & Feel. It contains two parts, a tabbed pane and a preview panel. The three tabs in the tabbed pane select chooser panels. The preview panel below the tabbed pane displays the currently selected color.
Here's the code from the example that creates a
JColorChooser
instance and adds it to a container:Thepublic class ColorChooserDemo extends JPanel ... { public ColorChooserDemo() { super(new BorderLayout()); banner = new JLabel("Welcome to the Tutorial Zone!", JLabel.CENTER); banner.setForeground(Color.yellow); . . . tcc = new JColorChooser(banner.getForeground()); . . . add(tcc, BorderLayout.PAGE_END); }JColorChooser
constructor in the previous code snippet takes aColor
argument, which specifies the chooser's initially selected color. If you don't specify the initial color, then the color chooser displaysColor.white
. See theColor
API documentation for a list of color constants you can use.A color chooser uses an instance of
ColorSelectionModel
to contain and manage the current selection. The color selection model fires a change event whenever the user changes the color in the color chooser. The example program registers a change listener with the color selection model so that it can update the banner at the top of the window. The following code registers and implements the change listener:See How to Write a Change Listener for general information about change listeners and change events.tcc.getSelectionModel().addChangeListener(this); . . . public void stateChanged(ChangeEvent e) { Color newColor = tcc.getColor(); banner.setForeground(newColor); }A basic color chooser, like the one used in the example program, is sufficient for many programs. However, the color chooser API allows you to customize a color chooser by providing it with a preview panel of your own design, by adding your own chooser panels to it, or by removing existing chooser panels from the color chooser. Additionally, the
JColorChooser
class provides two methods that make it easy to use a color chooser within a dialog.The rest of this section discusses these topics:
- Another Example: ColorChooserDemo2
- Showing a Color Chooser in a Dialog
- Removing or Replacing the Preview Panel
- Creating a Custom Chooser Panel
- The Color Chooser API
- Examples that Use Color Choosers
Now let's turn our attention to ColorChooserDemo2, a modified version of the previous demo program that uses more of theJColorChooser
API. You can run ColorChooserDemo2 using JavaTM Web Start. Here's a picture of ColorChooserDemo2:[PENDING: New snapshot needed (use v 1.4.2).] This program customizes the banner's text color chooser in these ways:
Removing or Replacing the Preview Panel covers the first customization. Creating a Custom Chooser Panel discusses the last two.
- Removes the preview panel
- Removes all of the default chooser panels
- Adds a custom chooser panel
This program also adds a button that brings up a color chooser in a dialog, which you can use to set the banner's background color.
TheJColorChooser
class provides two class methods to make it easy to use a color chooser in a dialog. ColorChooserDemo2 uses one of these methods,showDialog
, to display the background color chooser when the user clicks the Show Color Chooser... button. Here's the single line of code from the example that brings up the background color chooser in a dialog:The first argument is the parent for the dialog, the second is the dialog's title, and the third is the initially selected color.Color newColor = JColorChooser.showDialog( ColorChooserDemo2.this, "Choose Background Color", banner.getBackground());The dialog disappears under three conditions: the user chooses a color and clicks the OK button, the user cancels the operation with the Cancel button, or the user dismisses the dialog with a frame control. If the user chooses a color, the
showDialog
method returns the new color. If the user cancels the operation or dismisses the window, the method returnsnull
. Here's the code from the example that updates the banner's background color according to the value returned byshowDialog
:The dialog created byif (newColor != null) { banner.setBackground(newColor); }showDialog
is modal. If you want a non-modal dialog, you can useJColorChooser
'screateDialog
method to create the dialog. This method also lets you specify action listeners for the OK and Cancel buttons in the dialog window. UseJDialog
'sshow
method to display the dialog created by this method. For an example that uses this method, see Specifying Other Editors in the How to Use Tables section.
By default, the color chooser displays a preview panel. ColorChooserDemo2 removes the text color chooser's preview panel with this line of code:This effectively removes the preview panel because a plaintcc.setPreviewPanel(new JPanel());JPanel
has no size and no default view. To set the preview panel back to the default, usenull
as the argument tosetPreviewPanel
.To provide a custom preview panel, you also use
setPreviewPanel
. The component you pass into the method should inherit fromJComponent
, specify a reasonable size, and provide a customized view of the current color. To get notified when the user changes the color in the color chooser, the preview panel must register as a change listener on the color chooser's color selection model as described previously.
Version note: In some releases, you either could not replace the preview panel or could not remove it properly (the titled border would remain). We believe that both problems have been fixed as of 1.4.2. If your program depends on removing or replacing the preview panel, you should test it against all releases that it supports.
The default color chooser provides three chooser panels:You can extend the default color chooser by adding chooser panels of your own design with
- Swatches for choosing a color from a collection of swatches.
- HSB for choosing a color using the Hue-Saturation-Brightness color model.
- RGB for choosing a color using the Red-Green-Blue color model.
addChooserPanel
, or you can limit it by removing chooser panels withremoveChooserPanel
.If you want to remove all of the default chooser panels and add one or more of your own, you can do this with a single call to
setChooserPanels
. ColorChooserDemo2 uses this method to replace the default chooser panels with an instance ofCrayonPanel
, a custom chooser panel. Here's the call tosetChooserPanels
from that example:The code is straighforward: it creates an array containing the//Override the chooser panels with our own. AbstractColorChooserPanel panels[] = { new CrayonPanel() }; tcc.setChooserPanels(panels);CrayonPanel
. Next the code callssetChooserPanels
to set the contents of the array as the color chooser's chooser panels.
CrayonPanel
is a subclass ofAbstractColorChooserPanel
and overrides the five abstract methods defined in its superclass:
void buildChooser()
- Creates the GUI that comprises the chooser panel. The example creates four toggle buttons one for each crayon and adds them to the chooser panel.
void updateChooser()
- This method is called whenever the chooser panel is displayed. The example's implementation of this method selects the toggle button that represents the currently selected color.
public void updateChooser() { Color color = getColorFromModel(); if (Color.red.equals(color)) { redCrayon.setSelected(true); } else if (Color.yellow.equals(color)) { yellowCrayon.setSelected(true); } else if (Color.green.equals(color)) { greenCrayon.setSelected(true); } else if (Color.blue.equals(color)) { blueCrayon.setSelected(true); } }
String getDisplayName()
- Returns the display name of the chooser panel. The name is used on the tab for the chooser panel. Here's the example's
getDisplayName
method:public String getDisplayName() { return "Crayons"; }Icon getSmallDisplayIcon()
- Returns a small icon to represent this chooser panel. This is currently unused. Future versions of the color chooser might use this icon or the large one to represent this chooser panel in the display. The example's implementation of this method returns
null
.
Icon getLargeDisplayIcon()
- Returns a large icon to represent this chooser panel. This is currently unused. Future versions of the color chooser might use this icon or the small one to represent this chooser panel in the display. The example's implementation of this method returns
null
.
The following tables list the commonly usedJColorChooser
constructors and methods. Other methods you might call are listed in the API tables in The JComponent Class. The API for using color choosers falls into these categories:
- Creating and Displaying the Color Chooser
- Customizing the Color Chooser's GUI
- Setting or Getting the Current Color
Creating and Displaying the Color Chooser Method or Constructor Purpose JColorChooser()
JColorChooser(Color)
JColorChooser(ColorSelectionModel)Create a color chooser. The default constructor creates a color chooser with an initial color of Color.white
. Use the second constructor to specify a different initial color. TheColorSelectionModel
argument, when present, provides the color chooser with a color selection model.Color showDialog(Component, String, Color) Create and show a color chooser in a modal dialog. The Component
argument is the dialog's parent, theString
argument specifies the dialog's title, and theColor
argument specifies the chooser's initial color.JDialog createDialog(Component, String,
boolean, JColorChooser, ActionListener,
ActionListener)Create a dialog for the specified color chooser. As with showDialog
, theComponent
argument is the dialog's parent and theString
argument specifies the dialog's title. The other arguments are as follows: theboolean
specifies whether the dialog is modal, theJColorChooser
is the color chooser to display in the dialog, the firstActionListener
is for the OK button, and the second is for the Cancel button.
Customizing the Color Chooser's GUI Method Purpose void setPreviewPanel(JComponent)
JComponent getPreviewPanel()Set or get the component used to preview the color selection. To remove the preview panel, use new JPanel()
as an argument. To specify the default preview panel, usenull
.void setChooserPanels(AbstractColorChooserPanel[])
AbstractColorChooserPanel[] getChooserPanels()Set or get the chooser panels in the color chooser. void addChooserPanel(AbstractColorChooserPanel)
AbstractColorChooserPanel removeChooserPanel(AbstractColorChooserPanel)Add a chooser panel to the color chooser or remove a chooser panel from it. void setDragEnabled(boolean)
boolean getDragEnabled()Set or get the dragEnabled
property, which must be true to enable drag handling on this component. The default value is false. See Drag and Drop for more details. Introduced in 1.4.
Setting or Getting the Current Color Method Purpose void setColor(Color)
void setColor(int, int, int)
void setColor(int)
Color getColor()Set or get the currently selected color. The three integer version of the setColor
method interprets the three integers together as an RGB color. The single integer version of thesetColor
method divides the integer into four 8-bit bytes and interprets the integer as an RGB color as follows:void setSelectionModel(ColorSelectionModel)
ColorSelectionModel getSelectionModel()Set or get the selection model for the color chooser. This object contains the current selection and fires change events to registered listeners whenever the selection changes.
This table shows the examples that useJColorChooser
and where those examples are described.
Example Where Described Notes ColorChooserDemo This section Uses a standard color chooser. ColorChooserDemo2 This section Uses one customized color chooser and one standard color chooser in a dialog created with showDialog
.TableDialogEditDemo How to Use Tables Shows how to use a color chooser as a custom cell editor in a table. The color chooser used by this example is created with createDialog
.BasicDnD How to Use Drag and Drop and Data Transfer Uses a color chooser that's not in a dialog; demonstrates default drag-and-drop capabilities of Swing components, including color choosers. DragColorDemo How to Use Drag and Drop and Data Transfer Uses a color chooser without a dialog in a demonstration of importing Color
data.DragColorTextFieldDemo How to Use Drag and Drop and Data Transfer Similar to DragColorDemo, but demonstrates importing both Color
and text data.